/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.goldentrade.negocio.interfaces.impl;

import br.com.goldentrade.negocio.interfaces.impl.serviceLocator.ServiceLocator;
import br.com.goldentrade.negocio.beans.Operacao;
import br.com.goldentrade.negocio.interfaces.IOperacao;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

/**
 *
 * @author itaipu
 */
public class OperacaoImpl implements IOperacao {
    private EntityManager em;

    public void atualizar(Operacao operacao) {
         try {
            em = ServiceLocator.getEntityManager();
            em.getTransaction().begin();
            if(operacao.getCdOperacao() == null){
                em.persist(operacao);    
            }else{
                em.merge(operacao);
            }
            em.getTransaction().commit();
            ServiceLocator.leaveEntityManager(em);
            
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        
    }

    public void remover(Operacao operacao) {
         try{
            em = ServiceLocator.getEntityManager();
            em.getTransaction().begin();
            em.remove(operacao);
            em.getTransaction().commit();
            ServiceLocator.leaveEntityManager(em);
            
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
    }

    public Operacao selecionar(int cd) {
       Operacao o = null;
        try {
            em = ServiceLocator.getEntityManager();
            o = (Operacao) em.createNamedQuery("Operacao.findByCdOperacao").setParameter("cdOperacao", cd).getSingleResult();
            ServiceLocator.leaveEntityManager(em);
        } catch (NoResultException e) {
            System.out.println(e.getStackTrace());
        }
        return o;
        
    }

    public List<Operacao> selecionarTudo() {
        List<Operacao> operacoes = null;
        try {
            em = ServiceLocator.getEntityManager();
            operacoes = em.createNamedQuery("Operacao.findAll").getResultList();
            ServiceLocator.leaveEntityManager(em);
        } catch (Exception e) {
        }
        if(operacoes != null){
            return operacoes;
        }else{
            try {
                throw new Exception("Não possui dados");
            } catch (Exception ex) {
                Logger.getLogger(UsuarioImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }
    
}
